﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Secams.controller
{
    class SettingGroup
    {
        List< KeyValuePair<string, string> > _entries = new List<KeyValuePair<string,string>>();

        public List< KeyValuePair<string, string> > entries {
            get { return _entries; }
        }
        
        public string getSetting(string id)
        {
            foreach (KeyValuePair<string, string> entry in _entries)
            {
                if (entry.Key.Equals(id))
                    return entry.Value;
            }
            return null;
        }
    }

    class Settings
    {
        protected Dictionary<string, SettingGroup> _settingGroups = new Dictionary<string, SettingGroup>();


        public SettingGroup getGroup(string groupName)
        {
            return _settingGroups[groupName];
        }
        public string getSetting(string groupName, string id)
        {
            if (_settingGroups.ContainsKey(groupName))
            {
                return _settingGroups[groupName].getSetting(id);
            }
            return null;
        }


        public void loadXml(string xmlFilename)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlFilename);
            XmlNodeList selection = xmlDoc.SelectNodes("/Settings/SettingGroup");
            foreach (XmlNode scenarioNode in selection)
            {
                string name = getAttribute(scenarioNode, "name");

                SettingGroup settingGroup = loadSettingGroup(scenarioNode);

                _settingGroups[name] = settingGroup;
            }
        }

        protected SettingGroup loadSettingGroup(XmlNode scenarioNode)
        {
            SettingGroup retval = new SettingGroup();
            XmlNodeList children = scenarioNode.ChildNodes;
            foreach (XmlNode settingNode in children)
            {
                if (settingNode.NodeType == XmlNodeType.Element)
                {
                    XmlElement settingEl = (XmlElement)settingNode;
                    string id = getAttribute(settingEl, "id");
                    string value = getAttribute(settingEl, "value");

                    retval.entries.Add(new KeyValuePair<string, string>(id, value));
                }
            }
            return retval;
        }

        string getAttribute(XmlNode node, string attribName)
        {
            if (attribName == null) return null;
            XmlAttribute attrib = node.Attributes[attribName];
            if (attrib != null)
                return node.Attributes[attribName].Value;
            else return null;
        }
    }
}
